package apiday07.homework;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket;
    private ExecutorService threadPool;

    //初始化
    public Server() {
        System.out.println("正在启动服务器...");
        try {
            serverSocket = new ServerSocket(8888);
            System.out.println("服务器启动成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void start() {
        int count = 0;
        threadPool = Executors.newFixedThreadPool(5);
        System.out.println("等待用户连接...");
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                count++;
                System.out.println("用户" + count + "已连接");
                ClientHandler handler = new ClientHandler(socket, count);
                threadPool.execute(handler);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        int count;

        public ClientHandler(Socket socket, int count) {
            this.socket = socket;
            this.count = count;
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while (true) {
                    if ((line = br.readLine()) != null) {
                        System.out.println("用户" + count + "说：" + line);
                    } else {
                        System.out.println("用户" + count + "已断开连接！");
                        break;
                    }
                }
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

